package com.coder.network.response

import android.util.Log
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException

/**
 * @author yuhushuan
 * @ClassName: ProgressResponseBody
 * @Description: 封装带有进度的响应体
 * @date 17-1-25 11:25
 */
class ProgressResponseBody(
        /**
         * 实际待包装的响应体
         */
        private val mResponseBody: ResponseBody,
        /**
         * 进度回调接口
         */
        private val mListener: ProgressResponseListener?) : ResponseBody() {
    /**
     * 包装完成的BufferedSource
     */
    private var mBufferedSource: BufferedSource? = null
    override fun contentType(): MediaType? {
        Log.e(tag, "contentType()")
        return mResponseBody.contentType()
    }

    override fun contentLength(): Long {
        Log.e(tag, "contentLength()")
        return mResponseBody.contentLength()
    }

    override fun source(): BufferedSource {
        Log.e(tag, "source()")
        if (mBufferedSource == null) {
            mBufferedSource = Okio.buffer(source(mResponseBody.source()))
        }
        return mBufferedSource!!
    }

    private fun source(source: Source): Source {
        Log.e(tag, "source()")
        return object : ForwardingSource(source) {
            //当前读取字节数
            var totalBytesRead = 0L
            @Throws(IOException::class)
            override fun read(sink: Buffer, byteCount: Long): Long {
                val bytesRead = super.read(sink, byteCount)
                //增加当前读取的字节数，如果读取完成了bytesRead会返回-1
                totalBytesRead += if (bytesRead == -1L) 0 else bytesRead
                //回调，如果contentLength()不知道长度，会返回-1
                mListener?.onResponseProgress(totalBytesRead, mResponseBody.contentLength(), bytesRead == -1L)
                return bytesRead
            }
        }
    }

    companion object {
        private const val tag = "ProgressResponseBody"
    }

    init {
        Log.e(tag, "ProgressResponseBody()")
    }
}